#include "ItemEditDlg.h"

ItemEditDlg::ItemEditDlg( const QVector<QString> headers, int fieldNumber, int keyField, QWidget* parent ) : QDialog( parent )
{
    setWindowTitle( tr("Item") );

    KeyField = keyField;
    FieldNumber = fieldNumber;
    VisibleNumber = headers.size();

    LabelsLayout = new QVBoxLayout();
    EditLinesLayout = new QVBoxLayout();

    QLabel* TLabel;
    QLineEdit* TEdit;

    for (int i=0; i<VisibleNumber; i++){
        TLabel = new QLabel( headers[i] );
        TEdit = new QLineEdit();

        Labels.push_back( TLabel );
        Edits.push_back( TEdit );

        LabelsLayout->addWidget( Labels[i] );
        EditLinesLayout->addWidget( Edits[i] );
    }

    EditFieldLayout = new QHBoxLayout();
    EditFieldLayout->addLayout( LabelsLayout );
    EditFieldLayout->addLayout( EditLinesLayout );

    OkButton = new QPushButton(tr("OK"));
    CancelButton = new QPushButton(tr("Cancel"));

    ControlButtonsLayout = new QHBoxLayout();
    ControlButtonsLayout->addWidget( OkButton );
    ControlButtonsLayout->addWidget( CancelButton );

    ItemDialogLayout = new QVBoxLayout();
    ItemDialogLayout->addLayout( EditFieldLayout );
    ItemDialogLayout->addLayout( ControlButtonsLayout );

    connect( OkButton, SIGNAL(clicked()), this, SLOT(okPressed()) );
    connect( CancelButton, SIGNAL( clicked() ), this, SLOT( close() ) );
    for (int i=0; i<VisibleNumber-1; i++)
        connect( Edits[i], SIGNAL( returnPressed() ), Edits[i+1], SLOT( setFocus() ) );
    connect( Edits[VisibleNumber-1], SIGNAL( returnPressed() ), OkButton, SLOT( setFocus() ) );

    this->setLayout( ItemDialogLayout );

}

bool ItemEditDlg::SetItem( const ItemType &item )
{
    if ( item.GetFieldNumber() != FieldNumber ) return false;

    this->item = item;

    if ( item.Get( KeyField ) == "" ){
        for ( int i=0; i<VisibleNumber; i++ )
            Edits[i]->setText( "" );
        Edits[KeyField]->setEnabled( true );
    } else {
        for ( int i=0; i<VisibleNumber; i++ )
            Edits[i]->setText( item.Get( i ) );
        Edits[KeyField]->setEnabled( false );
    }

    return true;
}

void ItemEditDlg::okPressed()
{
    for ( int i=0; i<VisibleNumber; i++ )
        item.Set( i, Edits[i]->text() );

    emit ItemMade( item );
}

ItemEditDlg::~ItemEditDlg()
{
    for (int i=0; i<VisibleNumber; i++ ){
        delete Labels[i];
        delete Edits[i];
    }

    delete LabelsLayout;
    delete EditLinesLayout;
    delete ControlButtonsLayout;
    delete EditFieldLayout;
    delete ItemDialogLayout;

    delete OkButton;
    delete CancelButton;
}
